import os
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.db.models import Q
from PetNetadmin.serializers import OrderSerializer
from rest_framework import status
from utils.pagination import PetMessagePagination
from utils.imageupload import ImageUpload
from NetShop.models import Order
from admincharge.utils.jwt import MyJWTAuthentication


class GetAllOrderMessage(APIView):
    authentication_classes = [MyJWTAuthentication]
    def get(self, request):
        print(request.GET.get)
        order_id = request.GET.get('order_id')
        mobile = request.GET.get('mobile')
        price = request.GET.get('totalprice')
        order_time = request.GET.get('order_time')
        # 构建查询条件
        conditions = Q()
        if order_id:
            conditions &= Q(order_id=order_id)
        if mobile:
            conditions &= Q(mobile=mobile)
        if price:
            conditions &= Q(price=price)
        if order_time:
            conditions &= Q(order_time__contains=order_time)
        # 应用查询条件或返回所有数据
        if conditions:
            queryset = Order.objects.filter(conditions)
        else:
            queryset = Order.objects.all()
        # 分页处理
        paginator = PetMessagePagination()
        result_page = paginator.paginate_queryset(queryset, request)
        serializer = OrderSerializer(instance=result_page, many=True)

        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return paginator.get_paginated_response(result)
# 删除单个数据
@api_view(['POST'])
def deleteOneOrdermsg(request, id):
    try:
        orderMsg = Order.objects.get(pk=id)
        orderMsg.delete()
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except Order.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


# 删除多个数据时
@api_view(['POST'])
def deleteManyOrdermsg(request):
    try:
        ids = request.data['Ids']
        # 用来保存被删除对象的imgsurl字段
        # deleted_imgsurls = []
        for id in ids:
            pet_message = Order.objects.get(id=id)
            pet_message.delete()
        # print(deleted_imgsurls)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except Order.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)
